import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    redirect: '/login',  // 修改为默认跳转到登录界面
    meta: { requiresAuth: false }
  },
  {
    path: '/booking',
    name: 'UserBooking',
    component: () => import('@/views/UserBooking.vue'),
    meta: { requiresAuth: false }  // 允许未登录用户访问
  },
  {
    path: '/admin',
    name: 'AdminDashboard',
    component: () => import('@/views/AdminDashboard.vue'),
    meta: { requiresAuth: true, requiresAdmin: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// Navigation guards
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 需要认证但未登录 → 跳转登录页
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } 
  // 需要管理员权限但不是管理员 → 跳转预定页
  else if (to.meta.requiresAdmin && authStore.user?.role !== 'admin') {
    next('/booking')
  } 
  // 已登录访问登录页 → 根据角色跳转
  else if (to.path === '/login' && authStore.isAuthenticated) {
    // ✅ 管理员跳转到管理界面
    if (authStore.user?.role === 'admin') {
      next('/admin')
    } 
    // ✅ 普通用户跳转到预定界面
    else {
      next('/booking')
    }
  } 
  else {
    next()
  }
})

export default router